package cn.edu.neu.lab603.cloudeval.entity.model

import java.util.Random
import java.util.concurrent.atomic.AtomicInteger


/** 随机资源模型。
  *
  * Created by yfwz100 on 2016/11/3.
  */
class RandomResModel(val minVal: Int, val maxVal: Int, val maxSpec: Int) extends ResModel {

  assert(minVal <= maxVal, "Min value should be less than or equal to max value.")
  assert(maxVal <= maxSpec, "Max value should be less than specification value.")

  private val counterDown = new AtomicInteger
  private val random = new Random()
  private var value = minVal
  private var next = minVal

  /** 根据时钟周期更新当前利用率模型。
    *
    * @param clock 时钟
    */
  override def update(clock: Int): Unit = {
    if (counterDown.decrementAndGet <= 0) {
      value = next
      next = minVal + random.nextInt(maxVal - minVal)

      // 如果当前值越大，那么下一次更新的时间越短
      counterDown.lazySet(
        random.nextInt(1 + (10 * Math.sqrt((next - minVal).toDouble / (maxVal - minVal))).toInt)
      )
    } else {
      next = value
    }
  }

  /** 规格大小。 */
  override def getMax: Int = maxSpec

  /** 当前利用率的值。 */
  override def getValue: Int = value

  /** 下一帧请求值。 */
  override def getNext: Int = next
}

object RandomResModel {
  def apply(minVal: Int, maxVal: Int, maxSpec: Int): RandomResModel =
    new RandomResModel(minVal, maxVal, maxSpec)
}